package com.yuanyu.controller.admin;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.yuanyu.common.util.ResultInfoUtil;
import com.yuanyu.model.vo.LoginVO;
import com.yuanyu.model.vo.PasswordVO;
import com.yuanyu.model.vo.ResultInfo;
import com.yuanyu.server.ILoginServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private ILoginServer loginServer;

    private static String TOKEN;

    /**
     * 验证码生成
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/captcha")
    public void createCaptcha(HttpServletResponse response) throws IOException {
        System.out.println("========验证码生成=========");
        RandomGenerator randomGenerator = new RandomGenerator("1234567890", 4);
        // 定义图形验证码的长和宽
//        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 定义GIF验证码的长、宽
        GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 85);
        captcha.setGenerator(randomGenerator);
        // 重新生成code
        captcha.createCode();
        //response.getOutputStream()是获取HTTP响应的输出流，通常用于向客户端发送二进制数据，比如图片或文件。
        captcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();
        TOKEN = captcha.getCode();
        System.out.println("New_TOKEN:"+TOKEN);
        System.out.println("=========================");
    }

    @GetMapping("/Token")
    public String getToken(){
        return TOKEN;
    }

    @PostMapping("/login")
    public ResultInfo login(@RequestBody LoginVO loginVO)      {
        if (!loginVO.getToken().equals(TOKEN)) {
            return ResultInfoUtil.buildError("验证码错误");
        }
        return ResultInfoUtil.buildSuccess("登录成功", loginServer.login(loginVO));
    }

    @PostMapping("/updatePassword/{username}")
    public ResultInfo updatePassword(@RequestBody PasswordVO passwordVO,@PathVariable("username") String username){
        System.out.println("username:" + username);
        System.out.println("passwordVO:"+passwordVO);
        return ResultInfoUtil.buildSuccess(loginServer.updatePassword(username, passwordVO),null);
    }
}
